<?php

// 上传函数
function uploads($maxsize,$type,$pathHead,$posterName) {
// post name的名字
$posterName = $posterName;
// 判断文件上传错误
switch ($_FILES['myfile']['error']) {
	case 1:
		exit('文件超过php.ini的限制');
		break;
	case 2:
		exit('文件超过html的限制');
		break;
	case 3:
		exit('文件上传不完整');
		break;
	case 4:
		exit('没有选择文件');
		break;
	case 6:
		exit('服务器内部错误');
		break;
	case 7:
		exit('服务器内部错误');
		break;
}
// 定义允许上传的最大文件大小
$maxsize = $maxsize;
if ($_FILES['myfile']['size']>$maxsize) {
	exit('文件太大');
}
// 自定义允许的图片类型
$type = ['image/jpeg','image/jpg','image/pjpeg','image/png','image/gif'];
// in_array判断某元素是否在某数组里面
// var_dump 判断boolean 并输出
if (!in_array($_FILES['myfile']['type'],$type)) {
    exit('文件类型不合法');
}

$tmp = $_FILES['myfile']['tmp_name'];
//获取文件的扩展名字
$ext = pathinfo($_FILES['myfile']['name'],PATHINFO_EXTENSION);
//随机生成文件名
$filename = randomName();
$fullname = $filename . '.' . $ext;
$pathHead = $pathHead;
$dest = $pathHead . $fullname;
// 将临时文件夹移动到目标位置
move_uploaded_file($tmp, $dest);
}

function randomName() {
	$String = '';
    for ($i=0; $i < 6; $i++) { 
    	// mt_rand(0,2)生成0到2之间的随机整数
	    switch (mt_rand(0,2)) {
	    	case 0:
	    	    // String .= String2 字符串拼接
	    	    // chr(ASCALL码) 能将ASCALL转化为对应字符
	    	    // 97 到 122  大写26 
	    		$String .= chr(mt_rand(97,122)); 
	    		break;
	    	case 1:
	    	     // 65 到 90  小写26 
	    		$String .= chr(mt_rand(65,90)); 
	    		break;
	    	case 2:
	    	    // 0 到 9  数字 
	    		$String .= chr(mt_rand(48,57)); 
	    		break;
	    }
    }
    return $String;
}

$pathHead = 'H:/test/';
$maxsize = 1024*1024*1024*3;
$type = ['image/jpeg','image/jpg','image/pjpeg','image/png','image/gif'];
$posterName = 'myfile'; 

uploads($maxsize,$type,$pathHead,$posterName);